package com.example.music.activity; // 包名改为 activity

import android.app.AlertDialog;
import android.os.Bundle;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.music.R;
import com.example.music.adapter.PlaySongListAdapter;
import com.example.music.db.PlaylistDAO;
import com.example.music.model.Song;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
import java.util.List;

public class PlaylistActivity extends AppCompatActivity { // 改为继承 AppCompatActivity
    private RecyclerView recyclerView;
    private PlaySongListAdapter adapter;
    private List<PlaylistDAO.Playlist> playlists = new ArrayList<>();
    private PlaylistDAO playlistDao;

    @Override
    protected void onCreate(Bundle savedInstanceState) { // 使用 onCreate 代替 onCreateView
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_play_song_lists); // 设置布局

        recyclerView = findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(this)); // 上下文使用 this

        playlistDao = new PlaylistDAO(this); // 上下文使用 this
        loadPlaylists();

        FloatingActionButton fab = findViewById(R.id.fab_add_playlist);
        fab.setOnClickListener(v -> showCreatePlaylistDialog());
    }

    private void loadPlaylists() {
        playlists.clear();
        playlists.addAll(playlistDao.getAllPlaylists());
        if (adapter == null) {
            adapter = new PlaySongListAdapter(this, playlists, playlistDao); // 上下文使用 this
            recyclerView.setAdapter(adapter);
        } else {
            adapter.notifyDataSetChanged();
        }
    }

    private void showCreatePlaylistDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this); // 上下文使用 this
        builder.setTitle("新建歌单");

        final EditText input = new EditText(this); // 上下文使用 this
        builder.setView(input);

        builder.setPositiveButton("创建", (dialog, which) -> {
            String playlistName = input.getText().toString().trim();
            if (!playlistName.isEmpty()) {
                long playlistId = playlistDao.createPlaylist(playlistName);
                if (playlistId != -1) {
                    PlaylistDAO.Playlist playlist = new PlaylistDAO.Playlist();
                    playlist.setId(playlistId);
                    playlist.setName(playlistName);
                    playlist.setCreateTime(System.currentTimeMillis());

                    playlists.add(0, playlist);
                    adapter.notifyItemInserted(0);
                    recyclerView.smoothScrollToPosition(0);
                }
            }
        });

        builder.setNegativeButton("取消", null);
        builder.show();
    }
}